3 # DO NOT USE !!! Unless you want to help developping it.
5 # This file is an attempt to port the mysql database layer to postgreSQL. The
6 # only thing done so far is s/mysql/pg/ and dieing if function haven't been
9 # As said brion 07/06/2004 :
10 # "table definitions need to be changed. fulltext index needs to work differently
11 # things that use the last insert id need to be changed. Probably other things
12 # need to be changed. various semantics may be different."
16 require_once( "FulltextStoplist.php" );
17 require_once( "CacheManager.php" );
19 define( "DB_READ", -1 );
20 define( "DB_WRITE", -2 );
21 define( "DB_LAST", -3 );
23 define( "LIST_COMMA", 0 );
24 define( "LIST_AND", 1 );
25 define( "LIST_SET", 2 );
29 #------------------------------------------------------------------------------
31 #------------------------------------------------------------------------------
32 /* private */ var $mLastQuery = "";
33 /* private */ var $mBufferResults = true;
34 /* private */ var $mIgnoreErrors = false;
36 /* private */ var $mServer, $mUser, $mPassword, $mConn, $mDBname;
37 /* private */ var $mOut, $mDebug, $mOpened = false;
39 /* private */ var $mFailFunction;
41 #------------------------------------------------------------------------------
43 #------------------------------------------------------------------------------
45 # These set a variable and return the previous state
47 # Fail function, takes a Database as a parameter
48 # Set to false for default, 1 for ignore errors
49 function setFailFunction( $function ) { return wfSetVar( $this->mFailFunction
, $function ); }
51 # Output page, used for reporting errors
52 # FALSE means discard output
53 function &setOutputPage( &$out ) { return wfSetRef( $this->mOut
, $out ); }
55 # Boolean, controls output of large amounts of debug information
56 function setDebug( $debug ) { return wfSetVar( $this->mDebug
, $debug ); }
58 # Turns buffering of SQL result sets on (true) or off (false). Default is
59 # "on" and it should not be changed without good reasons.
60 function setBufferResults( $buffer ) { return wfSetVar( $this->mBufferResults
, $buffer ); }
62 # Turns on (false) or off (true) the automatic generation and sending
63 # of a "we're sorry, but there has been a database error" page on
64 # database errors. Default is on (false). When turned off, the
65 # code should use wfLastErrno() and wfLastError() to handle the
66 # situation as appropriate.
67 function setIgnoreErrors( $ignoreErrors ) { return wfSetVar( $this->mIgnoreErrors
, $ignoreErrors ); }
71 function lastQuery() { return $this->mLastQuery
; }
72 function isOpen() { return $this->mOpened
; }
74 #------------------------------------------------------------------------------
76 #------------------------------------------------------------------------------
81 # Can't get a reference if it hasn't been set yet
82 if ( !isset( $wgOut ) ) {
85 $this->mOut
=& $wgOut;
89 /* static */ function newFromParams( $server, $user, $password, $dbName,
90 $failFunction = false, $debug = false, $bufferResults = true, $ignoreErrors = false )
93 $db->mFailFunction
= $failFunction;
94 $db->mIgnoreErrors
= $ignoreErrors;
96 $db->mBufferResults
= $bufferResults;
97 $db->open( $server, $user, $password, $dbName );
101 # Usually aborts on failure
102 # If the failFunction is set to a non-zero integer, returns success
103 function open( $server, $user, $password, $dbName )
105 global $wgEmergencyContact;
108 $this->mServer
= $server;
109 $this->mUser
= $user;
110 $this->mPassword
= $password;
111 $this->mDBname
= $dbName;
116 if ( "" != $dbName ) {
117 # start a database connection
118 @$this->mConn
= pg_connect("host=$server dbname=$dbName user=$user password=$password");
119 if ( $this->mConn
== false ) {
120 wfDebug( "DB connection error\n" );
121 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
122 wfDebug( $this->lastError()."\n" );
128 # Closes a database connection, if it is open
129 # Returns success, true if already closed
132 $this->mOpened
= false;
133 if ( $this->mConn
) {
134 return pg_close( $this->mConn
);
140 /* private */ function reportConnectionError( $msg = "")
142 if ( $this->mFailFunction
) {
143 if ( !is_int( $this->mFailFunction
) ) {
144 $this->$mFailFunction( $this );
147 wfEmergencyAbort( $this );
151 # Usually aborts on failure
152 # If errors are explicitly ignored, returns success
153 function query( $sql, $fname = "" )
157 if ( $wgProfiling ) {
158 # generalizeSQL will probably cut down the query to reasonable
159 # logging size most of the time. The substr is really just a sanity check.
160 $profName = "query: " . substr( Database
::generalizeSQL( $sql ), 0, 255 );
161 wfProfileIn( $profName );
164 $this->mLastQuery
= $sql;
166 if ( $this->mDebug
) {
167 $sqlx = substr( $sql, 0, 500 );
168 $sqlx = wordwrap(strtr($sqlx,"\t\n"," "));
169 wfDebug( "SQL: $sqlx\n" );
171 if( $this->mBufferResults
) {
172 print $sql."<br/>\n";
173 $ret = pg_query( $this->mConn
, $sql);
175 // TODO FIXME : php doesnt get a postgre unbuffered query
176 // $ret = mysql_unbuffered_query( $sql, $this->mConn );
177 // I(hashar) am assuming that pg_send_query does the same
178 $ret = pg_send_query( $this->mConn
, $sql);
181 if ( false === $ret ) {
182 $error = pg_result_error( $this->mConn
);
183 // TODO FIXME : no error number function in postgre
184 // $errno = mysql_errno( $this->mConn );
185 if( $this->mIgnoreErrors
) {
186 wfDebug("SQL ERROR (ignored): " . $error . "\n");
188 wfDebug("SQL ERROR: " . $error . "\n");
190 // this calls wfAbruptExit()
191 $this->mOut
->databaseError( $fname, $sql, $error, 0 );
196 if ( $wgProfiling ) {
197 wfProfileOut( $profName );
202 function freeResult( $res ) {
203 if ( !@pg_free_result
( $res ) ) {
204 wfDebugDieBacktrace( "Unable to free PostgreSQL result\n" );
207 function fetchObject( $res ) {
208 @$row = pg_fetch_object( $res );
209 # FIXME: HACK HACK HACK HACK debug
212 # hashar : not sure if the following test really trigger if the object
214 if( pg_result_error($this->mConn
) ) {
215 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_result_error($this->mConn
) ) );
219 function numRows( $res ) {
220 @$n = pg_num_rows( $res );
221 if( pg_result_error($this->mConn
) ) {
222 wfDebugDieBacktrace( "SQL error: " . htmlspecialchars( pg_result_error($this->mConn
) ) );
226 function numFields( $res ) { return pg_num_fields( $res ); }
227 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
228 // TODO FIXME: need to implement something here
229 function insertId() {
230 //return mysql_insert_id( $this->mConn );
231 wfDebugDieBacktrace( "Database::insertId() error : not implemented for postgre" );
233 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
234 function lastErrno() { return $this->lastError(); }
235 function lastError() { return pg_result_error(); }
236 function affectedRows() { return pg_affected_rows( $this->mConn
); }
238 # Simple UPDATE wrapper
239 # Usually aborts on failure
240 # If errors are explicitly ignored, returns success
241 function set( $table, $var, $value, $cond, $fname = "Database::set" )
243 $sql = "UPDATE \"$table\" SET \"$var\" = '" .
244 wfStrencode( $value ) . "' WHERE ($cond)";
245 return !!$this->query( $sql, DB_WRITE
, $fname );
248 # Simple SELECT wrapper, returns a single field, input must be encoded
249 # Usually aborts on failure
250 # If errors are explicitly ignored, returns FALSE on failure
251 function get( $table, $var, $cond, $fname = "Database::get" )
253 $sql = "SELECT \"$var\" FROM \"$table\" WHERE ($cond)";
254 $result = $this->query( $sql, DB_READ
, $fname );
257 if ( pg_num_rows( $result ) > 0 ) {
258 $s = pg_fetch_object( $result );
260 pg_free_result( $result );
265 # More complex SELECT wrapper, single row only
266 # Aborts or returns FALSE on error
267 # Takes an array of selected variables, and a condition map, which is ANDed
268 # e.g. getArray( "cur", array( "cur_id" ), array( "cur_namespace" => 0, "cur_title" => "Astronomy" ) )
269 # would return an object where $obj->cur_id is the ID of the Astronomy article
270 function getArray( $table, $vars, $conds, $fname = "Database::getArray" )
272 $vars = implode( ",", $vars );
273 $where = Database
::makeList( $conds, LIST_AND
);
274 $sql = "SELECT \"$vars\" FROM \"$table\" WHERE $where LIMIT 1";
275 $res = $this->query( $sql, $fname );
276 if ( $res === false ||
!$this->numRows( $res ) ) {
279 $obj = $this->fetchObject( $res );
280 $this->freeResult( $res );
284 # Removes most variables from an SQL query and replaces them with X or N for numbers.
285 # It's only slightly flawed. Don't use for anything important.
286 /* static */ function generalizeSQL( $sql )
288 # This does the same as the regexp below would do, but in such a way
289 # as to avoid crashing php on some large strings.
290 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
292 $sql = str_replace ( "\\\\", "", $sql);
293 $sql = str_replace ( "\\'", "", $sql);
294 $sql = str_replace ( "\\\"", "", $sql);
295 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
296 $sql = preg_replace ('/".*"/s', "'X'", $sql);
298 # All newlines, tabs, etc replaced by single space
299 $sql = preg_replace ( "/\s+/", " ", $sql);
302 $sql = preg_replace ('/-?[0-9]+/s', "N", $sql);
307 # Determines whether a field exists in a table
308 # Usually aborts on failure
309 # If errors are explicitly ignored, returns NULL on failure
310 function fieldExists( $table, $field, $fname = "Database::fieldExists" )
312 $res = $this->query( "DESCRIBE '$table'", DB_READ
, $fname );
319 while ( $row = $this->fetchObject( $res ) ) {
320 if ( $row->Field
== $field ) {
328 # Determines whether an index exists
329 # Usually aborts on failure
330 # If errors are explicitly ignored, returns NULL on failure
331 function indexExists( $table, $index, $fname = "Database::indexExists" )
333 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
334 # SHOW INDEX should work for 3.x and up:
335 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
336 // FIXME: hashar : probably need investigation here
337 $sql = "SELECT 'INDEX' FROM '$table'";
338 $res = $this->query( $sql, DB_READ
, $fname );
345 while ( $row = $this->fetchObject( $res ) ) {
346 if ( $row->Key_name
== $index ) {
354 function tableExists( $table )
356 $old = $this->mIgnoreErrors
;
357 $this->mIgnoreErrors
= true;
358 $res = $this->query( "SELECT 1 FROM '$table' LIMIT 1" );
359 $this->mIgnoreErrors
= $old;
361 $this->freeResult( $res );
368 function fieldInfo( $table, $field )
370 $res = $this->query( "SELECT * FROM '$table' LIMIT 1" );
371 $n = pg_num_fields( $res );
372 for( $i = 0; $i < $n; $i++
) {
374 wfDebugDieBacktrace( "Database::fieldInfo() error : mysql_fetch_field() not implemented for postgre" );
375 $meta = mysql_fetch_field( $res, $i );
376 if( $field == $meta->name
) {
383 # INSERT wrapper, inserts an array into a table
384 # Keys are field names, values are values
385 # Usually aborts on failure
386 # If errors are explicitly ignored, returns success
387 function insertArray( $table, $a, $fname = "Database::insertArray" )
389 $sql1 = "INSERT INTO '$table' (";
390 $sql2 = "VALUES (" . Database
::makeList( $a );
392 foreach ( $a as $field => $value ) {
399 $sql = "$sql1) $sql2)";
400 return !!$this->query( $sql, $fname );
403 # A cross between insertArray and getArray, takes a condition array and a SET array
404 function updateArray( $table, $values, $conds, $fname = "Database::updateArray" )
406 $sql = "UPDATE '$table' SET " . $this->makeList( $values, LIST_SET
);
407 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
408 $this->query( $sql, $fname );
411 # Makes a wfStrencoded list from an array
412 # $mode: LIST_COMMA - comma separated, no field names
413 # LIST_AND - ANDed WHERE clause (without the WHERE)
414 # LIST_SET - comma separated with field names, like a SET clause
415 /* static */ function makeList( $a, $mode = LIST_COMMA
)
419 foreach ( $a as $field => $value ) {
421 if ( $mode == LIST_AND
) {
429 if ( $mode == LIST_AND ||
$mode == LIST_SET
) {
432 if ( !is_numeric( $value ) ) {
433 $list .= "'" . wfStrencode( $value ) . "'";
441 function startTimer( $timeout )
444 wfDebugDieBacktrace( "Database::startTimer() error : mysql_thread_id() not implemented for postgre" );
445 $tid = mysql_thread_id( $this->mConn
);
446 exec( "php $IP/killthread.php $timeout $tid &>/dev/null &" );
455 #------------------------------------------------------------------------------
457 #------------------------------------------------------------------------------
459 /* Standard fail function, called by default when a connection cannot be established
460 Displays the file cache if possible */
461 function wfEmergencyAbort( &$conn ) {
462 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgSiteNotice, $wgOutputEncoding;
464 header( "Content-type: text/html; charset=$wgOutputEncoding" );
465 $msg = $wgSiteNotice;
466 if($msg == "") $msg = wfMsgNoDB( "noconnect" );
469 if($wgUseFileCache) {
474 $t = Title
::newFromURL( $title );
475 } elseif (@$_REQUEST['search']) {
476 $search = $_REQUEST['search'];
477 echo wfMsgNoDB( "searchdisabled" );
478 echo wfMsgNoDB( "googlesearch", htmlspecialchars( $search ), $wgInputEncoding );
481 $t = Title
::newFromText( wfMsgNoDB( "mainpage" ) );
485 $cache = new CacheManager( $t );
486 if( $cache->isFileCached() ) {
487 $msg = "<p style='color: red'><b>$msg<br />\n" .
488 wfMsgNoDB( "cachederror" ) . "</b></p>\n";
490 $tag = "<div id='article'>";
494 $cache->fetchPageText() );
498 /* Don't cache error pages! They cause no end of trouble... */
499 header( "Cache-control: none" );
500 header( "Pragma: nocache" );
505 function wfStrencode( $s )
507 return addslashes( $s );
510 # Ideally we'd be using actual time fields in the db
511 function wfTimestamp2Unix( $ts ) {
512 return gmmktime( ( (int)substr( $ts, 8, 2) ),
513 (int)substr( $ts, 10, 2 ), (int)substr( $ts, 12, 2 ),
514 (int)substr( $ts, 4, 2 ), (int)substr( $ts, 6, 2 ),
515 (int)substr( $ts, 0, 4 ) );
518 function wfUnix2Timestamp( $unixtime ) {
519 return gmdate( "YmdHis", $unixtime );
522 function wfTimestampNow() {
524 return gmdate( "YmdHis" );
527 # Sorting hack for MySQL 3, which doesn't use index sorts for DESC
528 function wfInvertTimestamp( $ts ) {